<?php
//require_once ("C_krn_consts.php");
require_once ("C_krn_audit.php");
//require_once ("C_krn_exception.php");

// Funciones utiles
class c_krn_crypt {
	
	// Evitamos el clonaje del objeto. Patrón Singleton
	private function __clone() {
	}
	private function __wakeup() {
	}
	private static $_instance;
	public static function getInstance() {
		if (! (self::$_instance instanceof self)) {
			self::$_instance = new self ();
		}
		
		return self::$_instance;
	}
	function __construct() {
		global $cAUDIT;
		$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "::constructor (" . __CLASS__ . ")" );
	}
	
	// Cuando se cifra un email y sale el caracter + y / los cambio
	function base64url_encode($str) {
		  return strtr(base64_encode($str), '+/', '-_');
	}
	function base64url_decode($base64url) {
		  return base64_decode(strtr($base64url, '-_', '+/'));
	}
	
	// Función de encrptado
	function getCRYPT($cadena) {
		try {
			global $cAUDIT;
			$msg_pln = $cadena;
			$msg_cry = trim ( base64_encode ( mcrypt_encrypt ( MCRYPT_RIJNDAEL_256, SEMILLA, $msg_pln, MCRYPT_MODE_ECB, mcrypt_create_iv ( mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB ), MCRYPT_RAND ) ) ) );
			
			$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, 'CRYPT: PLAIN -> {' . $msg_pln . '} CRYPT -> {' . $this->base64url_encode($msg_cry) . '}' );
			
			return $this->base64url_encode($msg_cry);
		} catch ( Exception $e ) {
			$cAUDIT->AddAudit ( AUDIT_DB_SQL_FETCH, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $e->getMessage () );
		}
	}
	
	function getDECRYPT($cadena) {
		try {
			global $cAUDIT;
			$msg_cry = $this->base64url_decode($cadena);
			$msg_pln = trim ( mcrypt_decrypt ( MCRYPT_RIJNDAEL_256, SEMILLA, base64_decode ( $msg_cry ), MCRYPT_MODE_ECB, mcrypt_create_iv ( mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB ), MCRYPT_RAND ) ) );
			
			$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, 'DECRYPT: CRYPT -> {' . $cadena . '} PLAIN -> {' . $msg_pln . '}' );
			
			return $msg_pln;
		} catch ( Exception $e ) {
			$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $e->getMessage () );
		}
	}
}
;

// Instancia de la clase
try {
	// Instancia de la clase
	$cCRYPT = c_krn_crypt::getInstance ();
} catch ( Exception $e ) {
	global $IDIOMA, $language;
	echo $language [$IDIOMA] [59] . $e->getMessage ();
}

?>
